package com.timerdemo;

import android.content.Intent;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    private Timer timer;
    private TimerTask task = new TimerTask() {
        @Override
        public void run() {
            Message msg = Message.obtain();
            msg.what = 0;
            mHandler.sendMessage(msg);
        }
    };

    private UIHandler<MainActivity> mHandler = new UIHandler<MainActivity>(this) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                startActivity(new Intent(MainActivity.this, NewActivity.class));
                finish();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        timer = new Timer();
        timer.schedule(task, 3000);
    }

    @Override
    protected void onDestroy() {
        if (null != mHandler) {
            //删除消息，防止内存泄漏
            mHandler.removeCallbacksAndMessages(null);
        }
        if (null != timer) {
            timer.cancel();
        }
        super.onDestroy();
    }
}
